"use client";
import { GroupType, PrizeTypes } from "@/api/home";
import Box from "@/components/Box";
import CustomTabs from "@/components/Tabs";
import { useRouter } from "@/i18n/routing";
import { useSystemStore } from "@/stores/useSystemStore";
import { getToken } from "@/utils/Cookies";
import { Toast } from "antd-mobile";
import clsx from "clsx";
import { useTranslations } from "next-intl";
import React, { FC, useState } from "react";
import HomeGames from "./HomeGames";

// import HomePrize from "./HomePrize";

const buttonGroup: any = [
    // {
    //     category_name: "sixth",
    //     isHot: false,
    //     url: "/freeGames",
    //     locale: true,
    //     lock: false,
    //     isAnimation: true,
    //     image: "/home/free.webp",
    // },
    // {
    //     icon: "shipin",
    //     category_name: "fourth",
    //     isHot: false,
    //     url: "/gameList?gameListFlag=10&type=1&bet_type=1&name=live",
    //     locale: true,
    //     lock: false,
    //     image: "/home/live.png",
    // },
    // {
    //     category_name: "replay",
    //     isHot: false,
    //     url: "/replayGames",
    //     locale: true,
    //     lock: false,
    //     image: "/home/money.webp",
    // },
    // {
    //     category_name: "history",
    //     isHot: true,
    //     url: "/gameList?pageType=1&name=History",
    //     locale: true,
    //     lock: false,
    //     image: "/home/history.webp",
    //     needLogin: true,
    // },
    // {
    //     image: "/home/favorite.webp",
    //     category_name: "Coletar",
    //     isHot: false,
    //     url: "/gameList?pageType=2&name=Favorite",
    //     locale: true,
    //     lock: false,
    //     needLogin: true,
    // },
] as const;

type TabItemType = (typeof buttonGroup)[number] & GroupType;
const TabItem = ({
    item,
    active,
    onClick,
}: {
    item: TabItemType;
    active?: boolean;
    onClick?: (item: TabItemType) => void;
}) => {
    const t = useTranslations("ButtonGroup");
    const router = useRouter();
    const handler = (item: TabItemType) => {
        if (!item.locale) {
            onClick && onClick(item);
            return;
        }

        if (item.lock) {
            Toast.show("It is under development.");
        } else {
            if (item.needLogin && !getToken()) {
                router.push("/login");
                return;
            }
            router.push(item.url);
        }
    };
    const cls = clsx("pro-iconfont text-[.16rem]", item && item.icon ? `pro-${item.icon}` : "");

    // const cls2 = clsx("iconfont text-[.34rem]", `icon-${item.icon}`);

    return (
        <div
            className={clsx(
                "relative flex cursor-pointer items-center rounded-[.1rem] bg-[var(--main-background)] px-[.1rem] py-[.04rem]",
                !!active ? "text-[#fff]" : "text-[var(--textColor2)]"
            )}
            onClick={() => handler(item)}
        >
            <div className="relative z-[2] inline-block flex w-[.24rem] items-center justify-center">
                {!item.image && (
                    <span
                        className={clsx(cls, !!active ? "text-[#fff]" : "text-[var(--textColor4)]")}
                    ></span>
                )}
                {item.image && (
                    <img
                        src={item.image}
                        style={{ height: ".24rem" }}
                        alt={item.url}
                        className={clsx(item.isAnimation ? "animate-slow-bounce" : "")}
                    ></img>
                )}
            </div>

            <div
                className={
                    "relative z-[2] min-w-[0] flex-1 whitespace-nowrap px-[.02rem] text-center text-[0.1rem]"
                }
            >
                {item.locale ? t(item.category_name) : item.category_name}
            </div>
            {/* {item.isHot && (
                <img
                    className={"absolute -top-[0.12rem] right-0 h-[0.21rem] w-[0.21rem]"}
                    src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAMvUlEQVR4nO2df3BU1RXHP7ubXyQIIYBaQX6rjNSCotRasKDtTKvOCNI/7A9bRPvDMdOqte2M09Zo61itP+I02jq21OqMbUdaQZ1pq3UkUu0gRaAz1UIFEkDUCoGEJOQHu69z9t63+/L2vd232ZfkBt935k2SzX3nnnu+99x77j337YuhYVkWeVGfWAUsBRYA8/MXjqCxHdgGbAAe9zRKUzL9IxZTVBQmpD5xE9AAjI+sXBLagUZtyywCE1KfmAGsi7whdIjXLAda0oJdhMQ9a6tPLNCuFpERPuZr2y7wkpxLSH2iVo930RA1dBivR59adw1eHtIYecawYLrXRD9wDlHzxp4TrulmYxlNyQ1+c0jD6GrLCYFVzka4CVn+YbfOCGCAzbND1o3xKuDYh8AAJuKk2MOpTlweUvVht8oIosyu2nsdEmHEEBFiGCJCDENEiGGICDEMESGGISLEMESEGIaIEMMQEWIYIkIMQ9mo0tYLchQgpS8bcX3F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A04fYf2KxmglpF2/lbTR5/9C0k36LZqNo+lFy6NxyFoPzMhDhhOP67IPDZ96pWE0EdKafpGvGoqKeUj9iPaWZVqG0RgNhMjwdIfu6RtKkLNBv1TeaG8xnZBmbcSw3mJtvLeYSogYa4WOlloClC8WxnqLiYTcoY21bojrsb1FvmJu+xDXFRgmESLD07l6eCrym2VKwjbdAe4Yxjp9YQIhMmlfq4enbSOoR4MJ3jLShDyko6fHR1gPGyPuLU5ChvNx1O060rlpmIenoBhub8k8y5clpCn9PoWhDgVleLpZ98JS1hTDAdtbbtZ6DxVaaUp6EKIwlJHNet3AIFseJqFR6908RDoNsLmbkKEwlnPLYyjWFMOBFh10hO0t7W6bDySkKdkS8oQWxpaHSQjbWxq0zTPIjbKakg16eCkFovDMELc8TEJY3vJbrxHJL+xdpW8oFkO95WESGrX3D6bzPqRtnANvQpqSR2hKriqyFwzXlodJOKLnxhUBI9RmR7jview3Ofh9u069vGQ2XelybXA7LdquQ8N1+jrRPSIIxEYyOoidnJA5VGyUuxPRpL7fJSbfnwL8H00xaYOiAaDOAAAAAElFTkSuQmCC"
                    alt=""
                />
            )} */}
        </div>
    );
};

interface Props {
    tabs: GroupType[];
    prize?: PrizeTypes[];
}
const Tabs: FC<Props> = (props) => {
    const { tabs, prize } = props;
    const router = useRouter();
    const { show_again_game, show_free_game } = useSystemStore((state) => {
        return {
            show_again_game: state.show_again_game,
            show_free_game: state.show_free_game,
        };
    });

    const [active, setActive] = useState<string | undefined>();
    const stickyRef = React.useRef<number>(0);
    const containerRef = React.useRef<number>(0);
    const handleRef = React.useRef<NodeJS.Timeout | null>(null);

    const newButtonGroup = buttonGroup.filter((item: any) => {
        if (item.url === "/freeGames" && show_free_game !== 1) {
            return false;
        }
        if (item.url === "/replayGames" && show_again_game !== 1) {
            return false;
        }
        return true;
    });

    const groupGames = React.useMemo(() => {
        return tabs[0]?.category;
    }, [tabs]);

    const tabData = React.useMemo(() => {
        return [...tabs, ...newButtonGroup].map((item, idx) => {
            const id = `${item.category_name}_${item.action_params}`;
            return {
                ...item,
                name: item.category_name,
                id,
                jump_id: item.action_params,
                headerRender: () => (
                    <Box
                        action={item.action_type}
                        actionData={item.action_params}
                        additional={{
                            6: () => {
                                setActive(id);
                            },
                            8: () => {
                                tabClick();
                                setActive(id);
                                selectHandler(id);
                            },
                        }}
                        pt={false}
                        pr={false}
                        pb={false}
                        pl={false}
                    >
                        <TabItem
                            item={item as TabItemType}
                            active={`${id}` === active || (!active && idx === 0)}
                        ></TabItem>
                    </Box>
                ),
            };
        });
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [tabs, active, newButtonGroup]);

    const tabClick = () => {
        if (handleRef.current) {
            clearTimeout(handleRef.current);
            handleRef.current = null;
        }
        handleRef.current = setTimeout(() => {
            handleRef.current = null;
        }, 1000);
    };

    const getTab = (id: string) => {
        let result = tabData.find((item: any) => {
            return item.id === id;
        });
        if (!result) {
            result = tabData[0];
        }
        return result;
    };

    React.useEffect(() => {
        initScroll();
        window.addEventListener("resize", () => {
            getContainerInfo();
            getStickyContainerInfo();
        });
        return () => {
            window.removeEventListener("resize", () => {
                getContainerInfo();
                getStickyContainerInfo();
            });
        };
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    const getStickyContainerInfo = () => {
        const dom = document.querySelector("#stickyContainer");
        if (dom) {
            stickyRef.current = dom.getBoundingClientRect().height;
        }
    };
    const getContainerInfo = () => {
        const dom = document.querySelector("#maincontainer");
        if (dom) {
            containerRef.current = dom.getBoundingClientRect().top;
        }
    };
    const initScroll = () => {
        const container = document.querySelector("#maincontainer");
        if (!container) {
            setTimeout(initScroll, 200);
            return;
        }
        container.addEventListener("scroll", doScorll);
    };

    const doScorll = () => {
        if (handleRef.current) return;
        let target = null;
        for (let i = 0; i < tabData.length; i++) {
            const element = tabData[i];
            if (element.action_type === 8) {
                const dom = document.querySelector(`#jump_${element.jump_id}`);
                if (dom) {
                    const boundInfo = dom.getBoundingClientRect();
                    if (!stickyRef.current) {
                        getStickyContainerInfo();
                    }
                    if (!containerRef.current) {
                        getContainerInfo();
                    }
                    if (boundInfo.top < stickyRef.current + containerRef.current + 10) {
                        target = element;
                    } else {
                        break;
                    }
                }
            }
            if (target) {
                setActive(target.id);
            }
        }
        // requestAnimationFrame(doScorll);
    };

    const selectHandler = (id?: string) => {
        if (!id) return;
        const toTab = getTab(id);
        if (toTab.action_type !== 8) return;

        const toDom = document.querySelector(`#jump_${toTab.jump_id}`);

        const container = document.querySelector("#maincontainer");
        if (!stickyRef.current) {
            getStickyContainerInfo();
        }
        if (!containerRef.current) {
            getContainerInfo();
        }
        if (toDom && container) {
            const boundInfo = toDom.getBoundingClientRect();
            const toScroll =
                container.scrollTop + boundInfo.top - containerRef.current - stickyRef.current;
            container.scrollTo({
                top: toScroll,
                behavior: "smooth",
            });
        }
    };

    return (
        <>
            <div
                className="homeTabsContainer sticky top-[0rem] z-[3] bg-[var(--primary1)] px-[.1rem] pb-[.05rem] pt-[.05rem]"
                id="stickyContainer"
            >
                <CustomTabs
                    items={tabData as any}
                    activeKey={active}
                    onChanage={(value) => {
                        setActive(value);
                    }}
                ></CustomTabs>
            </div>
            {/* <div className="sticky top-[0rem] z-[3] bg-[var(--primary1)] px-[.1rem] pb-[.05rem] pt-[.05rem]">
                <Swiper
                    slidesPerView={4.5}
                    spaceBetween={4}
                    // centeredSlides={true}
                    // centeredSlidesBounds
                >
                    {tabData?.map((group, index) => (
                        <SwiperSlide key={index}>
                            <Box
                                action={group.action_type}
                                actionData={group.action_params}
                                additional={{
                                    6: () => {
                                        setActive(index);
                                    },
                                }}
                                pt={false}
                                pr={false}
                                pb={false}
                                pl={false}
                            >
                                <TabItem
                                    item={group as TabItemType}
                                    active={index === active}
                                    // onClick={(event) => selectHandler(event, index)}
                                ></TabItem>
                            </Box>
                        </SwiperSlide>
                    ))}
                    <div className="absolute left-[0] bg-gradient-to-r from-[var(--gradient-left6)] to-[var(--gradient-right6)]">
                        2323
                    </div>
                </Swiper>
            </div> */}
            {/* <HomePrize data={prize}></HomePrize> */}

            <HomeGames groupGames={groupGames} />
        </>
    );
};

export default Tabs;
